 window.onload = function() {
                var labels = document.getElementsByClassName('button');
                for (var i = 0; i < labels.length; i++) {
                    disableSelection(labels[i]);
                }

            };
            function disableSelection(element) {
                if (typeof element.onselectstart != 'undefined') {
                    element.onselectstart = function() { return false; };
                } else if (typeof element.style.MozUserSelect != 'undefined') {
                    element.style.MozUserSelect = 'none';
                } else {
                    element.onmousedown = function() { return false; };
                }
            }


      var myObjects = {};
      var count = 0;
      var x1,x2,y1,y2;
      var spriteW = 0;
      var spriteH = 0;
      var mathW = 0;
      var mathH = 0;
      var mathX = 0;
      var mathY = 0;
      var imageUrl = '';
      var imgUpload = ''

       var mousePosX = 0;
       var mousePosY = 0;

        var zoomSlide = 2;

$(document).ready(function() {


  var uploader = new qq.FileUploader({
    // pass the dom node (ex. $(selector)[0] for jQuery users)
    element: document.getElementById('file-uploader'),
    // path to server-side upload script
    action: '/server/php.php',
    debug: true,
    allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
    sizeLimit: 1000000,
    messages: {
    // error messages, see qq.FileUploaderBasic for content
},
showMessage: function(message){ alert(message); },
onComplete: function(id, fileName, responseJSON){
    imgUpload = 'server/uploads/' + fileName;
    newSprite(imgUpload);
    $('#preview').css({'background-image' : 'url(' + imgUpload + ')'});
    $('#zoom').css({'background-image' : 'url(' + imgUpload + ')'});
    $("#image-url").val(fileName);
    $('#current-sprite').load(function(){
        $.post("/server/uploads/clear.php", { data: fileName } );
    });
}

});


	$(function() {
		$( "#ui-info" ).tabs();
	});

$('.opentab').click(function(){
    $('#ui-info').tabs('select', 2);
});

$('#ui-panel').draggable({handle: '#ui-header, h1', containment : 'document'});
$('#ui-info').draggable({handle: '.ui-tabs-nav', containment : 'document'});
$('#ui-preview').draggable({handle: '#ui-preview', containment : 'document'}).resizable();
$('#zoom-slider').slider({
			value:2,
			min: 2,
			max: 6,
			step: 0.1,
                        orientation: 'vertical',
			slide: function( event, ui ) {
                            zoomSlide = $( this ).slider( "option", "value");
			}
		});

$('input').click(function(){
   if ($(this).attr('title') == $(this).val()) {
        $(this).val('');
   }
});


// UI ELEMENTS

function updateVals() {

    if ($('.selected').length > 0) {

    $('.selected').data("test").xPos = $('.selected').css("left").replace(/[^\d\.]/g, '');
    $('.selected').data("test").yPos = $('.selected').css("top").replace(/[^\d\.]/g, '');
    $('.selected').data("test").xSize = $('.selected').css("width").replace(/[^\d\.]/g, '');
    $('.selected').data("test").ySize = $('.selected').css("height").replace(/[^\d\.]/g, '');
    } else {}

}

function updateForm() {
            $('.button').removeClass('opt-selected');
            var massVar = $('.selected').data("test").mass;
            var repeatVar = $('.selected').data("test").repeat;
            var typeVar = $('.selected').data("test").type;

            $('#boxW').val($('.selected').data("test").xSize);
            $('#boxH').val($('.selected').data("test").ySize);
            $('#boxX').val($('.selected').data("test").xPos);
            $('#boxY').val($('.selected').data("test").yPos);
            $('.mass .button[id=' + massVar + ']').addClass('opt-selected');
            $('.repeat .button[id=' + repeatVar + ']').addClass('opt-selected');
            $('.naming .button:contains("' + typeVar + '")').addClass('opt-selected');
            previewCSS();

}
function updateFields(e) {
            $('#boxname').val($('.selected').data("test").name);
}

// CHANGES

// Sprite URL

function changeSprite(e) {
   imageUrl = $("#image-url").val();

    $('#preview').css({
        'background-image' : 'url(' + imageUrl + ')'
    });
        $('#zoom').css(
        {'background-image' : 'url(' + imageUrl + ')'});
   newSprite(imageUrl);
}

function newSprite(theSprite) {

   $('#main img').remove();
   $('#main').prepend('<img src="' + theSprite + '" alt="Sprite" id="current-sprite" />');
   $('#current-sprite').load(function(){
       spriteW = $('#current-sprite').attr('width');
       spriteH = $('#current-sprite').attr('height');
       if (spriteW > $(window).width()) {
            $('#graph').css('width', spriteW);
       }
       if (spriteH > $(window).height()) {
            $('#graph').css('height', spriteH);
       }
   });
}

$('.spritechange').click(function(event){
   event.preventDefault();
   imageUrl = $(this).attr('href');

    $('#preview').css({
        'background-image' : 'url(' + imageUrl + ')'
    });
        $('#zoom').css(
        {'background-image' : 'url(' + imageUrl + ')'});
   newSprite(imageUrl);
});

$('#image-url').change(function(){
    changeSprite();
}).keydown(function(e) {
        if (e.which == 13) {
        changeSprite();
        }
}).blur(function(){

        changeSprite();
});

// Type
$('.naming .button').click(function(){
   $('.naming .button').removeClass('opt-selected');
   $(this).addClass('opt-selected');
   $('.selected').data("test").type = $(this).text();
});

// Name
$('#boxname').change(function(){
   $('.selected').data("test").name = $(this).val();
});
$('#boxname').keydown(function(e) {
        if (e.which == 13) {
   $('.selected').data("test").name = $(this).val();
        }
});

// Mass
$('.mass .button').click(function(){
   $('.mass .button').removeClass('opt-selected');
   $('.selected').data("test").mass = $(this).attr('id');
   $(this).addClass('opt-selected');
});
// Repeat
$('.repeat .button').click(function(){
   $('.repeat .button').removeClass('opt-selected');
   $('.selected').data("test").repeat = $(this).attr('id');
   $(this).addClass('opt-selected');
});



var inputHasFocus = false;

$("input, textarea").focusin(function () {
    inputHasFocus = true;
}).focusout(function () {
    inputHasFocus = false;
});

var shift = false;

$(document).keydown(function(e) {
        //alert(e.which);

        if (e.which == 16) {
            shift = true;
        }

        if ((shift == false) && (e.which == 90)) {
            $('body').toggleClass('zoomOn');
            $('#zoom .zoom-value').delay(200).fadeOut(400);
        }
        else if ((shift == true) && (e.which == 90)) {
            if (zoomSlide <= 8) {
            zoomSlide = zoomSlide + 2;
            } else {
                zoomSlide = 2;
            }
            zoomUpdate();
            $('#zoom .zoom-value').fadeIn(100).fadeOut(300);
    }
        else if (e.which == 13) {
            e.preventDefault();
            $('input').blur();
        }
        else if (e.which == 88) {
            $('body').toggleClass('crossOn');
        }
        else if ((shift == false) && (e.which == 37)) {

            var leftMove =  ($('.selected').data('test').xPos - 1);
            $('.selected').css('left', leftMove + 'px');

        }
        else if ((shift == true) && (e.which == 37)) {
            /*var leftWidth =  parseInt($('.selected').data('test').xSize);
            leftWidth = leftWidth + 1;
            $('.selected').css('width', leftWidth + 'px');
            leftMove =  ($('.selected').data('test').xPos - 1);
            $('.selected').css('left', leftMove + 'px');*/
            var leftWidth =  parseInt($('.selected').data('test').xSize);
            leftWidth = leftWidth - 1;
            $('.selected').css('width', leftWidth + 'px');
        }
        else if ((shift == false) && (e.which == 39)) {
            var rightMove =  parseInt($('.selected').data('test').xPos);
            rightMove = rightMove + 1;
            $('.selected').css('left', rightMove + 'px');
        }
        else if ((shift == true) && (e.which == 39)) {
            var rightWidth =  parseInt($('.selected').data('test').xSize);
            rightWidth = rightWidth + 1;
            $('.selected').css('width', rightWidth + 'px');
        }
        else if ((shift == false) && (e.which == 38)) {
            e.preventDefault();
            upMove =  ($('.selected').data('test').yPos - 1);
            $('.selected').css('top', upMove + 'px');
        }
        else if ((shift == true) && (e.which == 38)) {
            /*e.preventDefault();
            var upMove =  ($('.selected').data('test').yPos - 1);
            $('.selected').css('top', upMove + 'px');
            var topHeight =  parseInt($('.selected').data('test').ySize);
            topHeight = topHeight + 1;
            $('.selected').css('height', topHeight + 'px');*/
            var topHeight =  parseInt($('.selected').data('test').ySize);
            topHeight = topHeight - 1;
            $('.selected').css('height', topHeight + 'px');
        }
        else if ((shift == false) && (e.which == 40)) {
            e.preventDefault();
            var downMove =  parseInt($('.selected').data('test').yPos);
            downMove = downMove + 1;
            $('.selected').css('top', downMove + 'px');
        }
        else if ((shift == true) && (e.which == 40)) {
            e.preventDefault();
            var bottomHeight =  parseInt($('.selected').data('test').ySize);
            bottomHeight = bottomHeight + 1;
            $('.selected').css('height', bottomHeight + 'px');
        } else if ((!inputHasFocus) && ((e.which == 8) || (e.which == 46))) {
            $('.selected').remove();
            e.preventDefault();
        } else {}

});


$(document).keyup(function(e) {


        if (e.which == 16) {
            shift = false;
        }
        //alert($('.selected').css('left'));
        updateVals();
        //alert($('.selected').data('test').xPos);
        //alert(e.which);
        updateForm();
});



// CREATE BOX
$('#graph, #zoom, .crosshair, :not .box').mousedown(function(e) {
    
    $("#current").attr({ id: '' })

    x1 = e.pageX;
    y1 = e.pageY;
    mathX = e.pageX;
    mathY = e.pageY;

    $('.box').removeClass('selected');
    box = $('<div class="box selected" style="z-index:102;background-color:#FF3C00;opacity:0.6;position:absolute;width:0px;height:0px;"></div>').hide();
    box.data("test", { xPos: x1, yPos: y1, xSize: 0, ySize: 0, name: 'Untitled', mass : 'mass1', repeat : 'repeat1', type : '.' });
    $('body').append(box);

    box.attr({id: 'current'}).css({
    top: y1 , //offsets
    left: x1 //offsets
    }).fadeIn();


    updateFields();

});

/*
$('body, :not #ui-panel').mousemove(function(e) {



    if (e.pageY <= y1) {

    box.attr({id: 'current'}).css({
    top: y1 + (e.pageY - y1)
    });
}

    if (e.pageX <= x1) {

    box.attr({id: 'current'}).css({
    left: x1 + (e.pageX - x1) //offsets
    });
}


});*/



$('body, :not #ui-panel').mousemove(function(e) {


        $('#cross-vert').css('left', e.pageX ).text(e.pageX);
        $('#cross-horz').css('top', e.pageY).text(e.pageY);

        mousePosX = e.pageX;
        mousePosY = e.pageY;


   /* if (e.pageY < y1) {

    box.attr({id: 'current'}).css({
    height: 2
    });
} else {

        $("#current").css({
        height:Math.abs(e.pageY - y1) //offsets
        });
}

    if (e.pageX < x1) {

    box.attr({id: 'current'}).css({
    width: 2
    });
}else {

        $("#current").css({
        width:Math.abs(e.pageX - x1) //offsets
        });
}*/


        $("#current").css({
        width: (e.pageX - x1), //offsets
        height: (e.pageY - y1) //offsets
        });

        zoomUpdate();

        if ($('.box').length > 0) {
            updateVals();
            updateForm();
        }


});

function zoomUpdate() {

        $('#zoom').css(
        {
          'background-repeat' : 'no-repeat',
          'background-color' : '#fff',
          'top' : (mousePosY - 50) + 'px',
          'left' : (mousePosX - 50) + 'px',
          '-moz-background-size' : (spriteW * zoomSlide) + 'px ' + (spriteH * zoomSlide) + 'px',
          'background-size' : (spriteW * zoomSlide) + 'px ' + (spriteH * zoomSlide) + 'px',
          //'background-size' : (100 * zoomSlide) + '% ' + (100 * zoomSlide) + '%',
          'background-position' : (((mousePosX * zoomSlide) - 50) * -1) + 'px ' + (((mousePosY * zoomSlide) - 50) * -1) + 'px'
        });
        //-webkit-background-scale:' + (spriteW * 2) + 'px' + (spriteH * 2) + 'px;' + '-webkit-background-scale:' + '-' + (spriteW * 2) + 'px' + ' -' + (spriteH * 2) + 'px;'
        //$('#zoom').css('top', e.pageY).css('left', e.pageX);
        $('#zoom .zoom-value span').text(zoomSlide);

}


$('#graph, #zoom, .crosshair').mousedown(function() {
        $('input, textarea').addClass('no-select');
});

$('body, :not #ui-panel').mouseup(function(e) {


        $('input, textarea').removeClass('no-select');

        updateVals();
        updateForm();

        $('#current').resizable({
               resize: function(event, ui) {
               }
            }
            ).draggable({
               drag: function(event, ui) {
                   var checkLeft = parseInt($('.selected').css('left'));
                   if (checkLeft >= '0') {
                   } else {
                       $('.selected').text(checkLeft);
                      }
                    }
            , containment : 'document', snap: true, snapTolerance: 10 });
        $("#current").attr({ id: '' });



        $('.box').mousedown(function(){
            $('.box').removeClass('selected');
            $(this).addClass('selected');
            updateForm();
            updateFields();
       });


        $('.box').each(function() {
             if (($(this).css("width") == '0px') || ($(this).css("height") == '0px')) {
                    $(this).remove();
                } else {}});


            if ($('.box').hasClass('selected')) {
                $('.options').removeClass('disable');
            } else {
                $('.options').addClass('disable');}

});



$('#makeOutput').click(function(){

    var allNames = '';
    var allBoxes = $('.box').length;

        $('#output').text('');
        $('.box').each(function(i, val) {
            /*$('#output').append('\r\n' + $(this).data("test").type + $(this).data("test").name + '{width:' + $(this).data("test").xSize + 'px;height:' + $(this).data("test").ySize + 'px;background-position:-' + $(this).data("test").xPos + 'px -' + $(this).data("test").yPos + 'px;');

            if ($(this).data("test").mass == 'mass2') {
                $('#output').append('display:block;')
            } else if ($(this).data("test").mass == 'mass3') {
                $('#output').append('display:inline-block;')
            }

            if ($(this).data("test").repeat == 'repeat1') {
                $('#output').append('background-repeat:no-repeat;')
            } else if ($(this).data("test").repeat == 'repeat2') {
                $('#output').append('background-repeat:repeat-x;;')
            } else if ($(this).data("test").repeat == 'repeat3') {
                $('#output').append('background-repeat:repeat-y;;')
            } else if ($(this).data("test").repeat == 'repeat4') {
                $('#output').append('background-repeat:repeat;}')
            } else {}*/

            createCSS(this, '#output');


            i = i + 1;
            
            if (i == allBoxes) {
                allNames = allNames + $(this).data("test").type + $(this).data("test").name + ' ';
            } else {
                allNames = allNames + $(this).data("test").type + $(this).data("test").name + ', ';
            }

          });


        $('#output').append('\r\n' + allNames + '{background-image:url(' + imageUrl + ');}')
        $('#output').select();

});


function createCSS(item, where) {
    $(where).append('\r\n' + $(item).data("test").type + $(item).data("test").name + '{width:' + $(item).data("test").xSize + 'px;height:' + $(item).data("test").ySize + 'px;background-position:-' + $(item).data("test").xPos + 'px -' + $(item).data("test").yPos + 'px;');

            if ($(item).data("test").mass == 'mass2') {
                $(where).append('display:block;')
            } else if ($(item).data("test").mass == 'mass3') {
                $(where).append('display:inline-block;')
            }

            if ($(item).data("test").repeat == 'repeat1') {
                $(where).append('background-repeat:no-repeat;')
            } else if ($(item).data("test").repeat == 'repeat2') {
                $(where).append('background-repeat:repeat-x;;')
            } else if ($(item).data("test").repeat == 'repeat3') {
                $(where).append('background-repeat:repeat-y;;')
            } else if ($(item).data("test").repeat == 'repeat4') {
                $(where).append('background-repeat:repeat;}')
            } else {}
}
function previewCSS() {
    $('#ui-preview .prev-header span').text($('.selected').data("test").name);
    var prevHeader = $('.prev-header').height() + 24;
    var prevHeight = $('#ui-preview').height() - prevHeader;
    var prevBox = $('#preview').height();

    $('#ui-prev-wrap').css('height', prevHeight - 2);


    $('#preview').css({
        'margin-top' : ((prevHeight - prevBox) / 2),
        'width' : $('.selected').data("test").xSize + 'px',
        'height' : $('.selected').data("test").ySize + 'px',
        'background-position' : ($('.selected').data("test").xPos * -1) + 'px ' + ($('.selected').data("test").yPos * -1) + 'px'
    });

    //$('#preview').attr('style', 'margin-top:' + ((prevHeight - prevBox) / 2) + 'px;background-image:url(' + imageUrl + ');width:' + $('.selected').data("test").xSize + 'px;height:' + $('.selected').data("test").ySize + 'px;background-position:' + ($('.selected').data("test").xPos * -1) + 'px ' + ($('.selected').data("test").yPos * -1) + 'px;');
}

$('#info').click(function(){
    $('#ui-info').toggle();
});
$('#close-info').click(function(){
    $('#ui-info').hide();
});
$('#prev-btn').click(function(){
    $('#ui-preview').toggle();
    previewCSS();
});
$('#close-prev').click(function(){
    $('#ui-preview').hide();
});
$('.val').click(function(){

        $(this).select();

});



});